let {User} = require('../models');

let auth=require('../utils/auth');

//主页
let index_fn=async(ctx,next)=>{
    ctx.render('index.html')
}
//登录跳转
let login_fn = async (ctx, next) => {
    ctx.render('login.html');
}

//创建跳转
let create_fn=async(ctx,next)=>{
    ctx.render('create.html');
}
//注销
let logout_fn = async (ctx, next) => {
    ctx.redirect('/help');
}
//注销跳转
let helpLogout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.redirect('/login');
}
//注册跳转
let register_fn = async (ctx, next) => {
    ctx.render('register.html')
}

//登录的判断

let loginDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || '';
    let password = ctx.request.body.password || '';

    console.log(username);
    console.log(password);
    let res;
    let u1=await User.findOne({where:{
        username:username,
        password:password
    }}).then((row)=>{
        let user=JSON.stringify(row);
        let u2=JSON.parse(user);
        console.log(user);
        console.log(u2);
        
        if(user!=='null'){
            ctx.session.userId=row.id;
            ctx.session.userName=row.username;
            res={code:200,msg:'登录成功'};
        }else{
            res={code:1000,msg:'用户名或密码错误，请重试'};
        }
    });
    ctx.body=res;
}

//注册的判断

let registerDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || '';
    let password = ctx.request.body.password || '';
    let confirmpassword = ctx.request.body.confirmpassword || '';

    console.log(username);
    console.log(password);
    console.log(confirmpassword);

    if (username.length > 0 && password.length > 0 && confirmpassword.length > 0 && password === confirmpassword) {
        let userDemo=await User.findOne({ where: { username: username } });
        console.log(JSON.stringify(userDemo));
        let res='';

        // 如果有找到同名的用户，则返回提示消息，并且不创建用户；否则创建用户，并返回提示消息
        if(userDemo){
            // msg='当前用户名已经注册，请确认后重试';
            res={code:1000,msg:'当前用户名已经注册，请确认后重试'};
        }else{
            let u1=User.create({
                username: username,
                password: password
            });
            res={code:200,msg:'注册成功'};
        }

        ctx.body=JSON.stringify(res);
        // ctx.render('login.html');
    } else {
        console.log('用户名或密码不能为空；并且两次密码应该相同');
    }
}


module.exports={
    '/': ['get',auth,index_fn],
    '/login': ['get',auth, login_fn],
    '/logout': ['post', logout_fn],
    '/create':['get',create_fn],
    '/help': ['get', helpLogout_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
}